package engine.systems.render.tv
{
	import engine.classes.enumerations.SystemPriority;
	import engine.groups.Group;
	import engine.systems.update.GameSystem;
	
	import flash.display.Bitmap;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	
	/**
	 * The Recorder System duplicates a Display Object onto Bitmap Data. This can be used to copy a Display
	 * Object into a separate window to be used as a different camera or viewport.
	 */
	public class TVSystem extends GameSystem
	{
		private var matrix:Matrix = new Matrix();
		private var rect:Rectangle;
		private var scale:Number;
		
		public function TVSystem()
		{
			super(TVNode, updateNode, null, nodeRemoved);
			
			this.priority = SystemPriority.UPDATE;
		}
		
		private function updateNode(node:TVNode, time:Number):void
		{
			if(node.recorder.invalidate)
			{
				node.recorder.invalidate = false;
				node.recorder.data.fillRect(node.recorder.data.rect, 0);
				Bitmap(node.render.display).bitmapData = node.recorder.data;
			}
			
			if(node.recorder.display)
			{
				node.recorder.data.fillRect(node.recorder.data.rect, 0);
				
				if(node.recorder.fit)
				{
					rect = node.recorder.display.getBounds(node.recorder.display);
					scale = Math.min(node.recorder.data.width / rect.width, node.recorder.data.height / rect.height);
					
					matrix.createBox(scale, scale, 0, -rect.left * scale, -rect.top * scale);
				}
				else matrix.setTo(1, 0, 0, 1, -node.recorder.x, -node.recorder.y);
				
				node.recorder.data.draw(node.recorder.display, matrix);
			}
		}
		
		private function nodeRemoved(node:TVNode):void
		{
			node.recorder.destroy();
		}
	}
}